from vtk import vtkRenderer, vtkActor, vtkPolyDataMapper, vtkSphereSource, vtkPolyDataReader
from time import sleep, clock
from Sensor import Sensor
from numpy import matrix
from Recording import Recording

##  RecordingState contains the functionality behind the RecordingPanel.
class RecordingState:

    ##  The constructor of RecordingState.
    #   @param[in]  parent  The wx window parent (VisualizationState) of this Panel.
    #   @param[in]  main    Main wx.App derived instance.
    def __init__(self, parent, main):
        ##  The wx window parent (VisualizationState) of this Panel.
        self.parent = parent
        ##  Main wx.App derived instance.
        self.main = main
        ##  Flag indicating whether the playback is on or off.
        self.PLAYING = False
        ##  Flag indicating whether this is the first session or not.
        self.FIRST_TIME = True
        ##  List of recordings, each with its corresping frames.
        self.recordingSession = None
        ##  Flag that indicates whether the program is recording.
        self.RECORDING = False
        # Initiate VTK render window for this state.
        self.parent.InitiateVTK(self)
        self.parent.SetRenderActors(self,len(self.main.bonyLandmarks),len(self.main.sensors),len(self.main.GHJoints))

    ##  Toggles the playing of the visualization on and off.
    #   Is used to stop the visualization when the user is not in this panel.
    def OnTogglePlayPause(self):
        if self.PLAYING:
            self.PLAYING = False
        else:
            self.PLAYING = True
            self.Play()

    ##  Gets the following frame and visualizes it. Checks whether the RECORDING flag of the VisualizationState is on to save the frame.
    def Play(self):
        while self.PLAYING:
            startTime = clock()
            self.main.driver.SampleSensors()
            self.parent.update_actor_positions()
            if self.RECORDING:
                self.Record()
            endTime = clock()
            self.parent.main.Yield()

            if (endTime - startTime) < (1.0/self.parent.frameRate):
                sleep((1.0/self.parent.frameRate) - (endTime - startTime))

    ##  Records the current positions and rotations of the sensors.
    def Record(self):
        self.recordingSession.AddFrame(self.main)

    ##  Creates a new recording session.
    def newRecordingSession(self):
        self.recordingSession = Recording(self.main)